package org.ffmmx.gxhotel.controller;

import org.ffmmx.common.util.TokenUtil;
import org.ffmmx.gxhotel.model.Logon;
import org.ffmmx.gxhotel.model.Ok;
import org.ffmmx.gxhotel.model.Result;
import org.ffmmx.gxhotel.repository.stationlist.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Optional;

@RestController
public class UserCtrl {
    @Autowired
    private UserRepo userRepo;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<Logon> login(@RequestParam String userName, @RequestParam String passwd) {


        final Optional<Ok> oko = Optional.ofNullable(userRepo.findUserByUserNameAndAndPasswdAndAndValid(userName, passwd, true))
                .map(user -> {
                    final Logon logon = new Logon();
                    logon.setUserId(user.getId());
                    //默认三天
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_YEAR, 3);
                    logon.setExpireTime(calendar.getTime());
                    logon.setToken(TokenUtil.generateToken(user.getId().toString(), null, logon.getExpireTime()));
                    return new Ok(logon);
                });

        if (oko.isPresent()) {
            return oko.get();
        }
        else {
            final Result<Logon> failed = new Result<>();
            failed.setCode(0);
            failed.setSuccess(false);
            failed.setMsg("登录失败:用户名或者密码错误");
            return failed;
        }
    }
}
